﻿using Org.BouncyCastle.Utilities.Encoders;
using PasswdTool.Model;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Tables;

namespace PasswdTool
{
    public partial class LoginFrm : Form
    {
        public LoginFrm()
        {
            InitializeComponent();
        }

        private void NewLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            NewUserFrm newUserFrm = new NewUserFrm();
            newUserFrm.ShowDialog();
        }

        private void CancelBtn_Click(object sender, System.EventArgs e)
        {
            Application.Exit(new System.ComponentModel.CancelEventArgs());
        }

        private void OkBtn_Click(object sender, System.EventArgs e)
        {
            string name = nameTxb.Text;
            string passwd = passwdTxb.Text;
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("用户不能为空!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                nameTxb.Focus();
                return;
            }
            if (string.IsNullOrEmpty(passwd))
            {
                MessageBox.Show("密码不能为空!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                passwdTxb.Focus();
                return;
            }
            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(passwd));
            passwd = Base64.ToBase64String(bytes);
            UserModel model = new UserModel()
            {
                Name = name,
                Passwd = passwd
            };
            UserTable table = GlobalContainer.UserTable;
            var result = table.Query(model);
            if (result == null || result.Count == 0)
            {
                MessageBox.Show("用户名或密码错误!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            GlobalContainer.CurrentUser = result[0];
            this.Close();
        }
    }
}
